const WXuserInfo = require("./wxuserInfo.js");
import user from "../../core/user.js";
import ProjectDef from "../../core/ProjectDef.js";
import System_manager from "../../core/System_manager.js";
getApp().globalData.baseUrl = "https://zgxtserver.chenxifunds.com"
// getApp().globalData.baseUrl = "http://192.168.1.5:38184"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    usedLogin: false, //缓存判别是否登录过
    wxUserInfo: null, //小程序登录信息
    loginType: "oneClick", //一键登录 
    input: {},
    userName: '',
    accountValue: '',
    passwordValue: "",
    userInfo: {},
    userImage: '',
    globalData: {},
    phoneNumber: 0,
    textcontent:"提示：订阅",
  },


  /**
   * 1. 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
 
    let guid = "v2guid";
    var that = this;
    return
    wx.getStorage({
      key: "user",
      success: function (res) {
        getApp().globalData.access_token = wx.getStorageSync('access_token');
        getApp().globalData.openid = wx.getStorageSync('openid');
        getApp().globalData.user = wx.getStorageSync('user');
        getApp().globalData.sys = new System_manager();
        getApp().globalData.sys.load()
          .then(
            res5 => {
              console.log(getApp().globalData.sys)
              ProjectDef.loadList()
                .then(
                  res4 => {
                    console.log(res4);
                    wx.navigateTo({
                      url: '../check/check'
                    });
                  }
                )
            }
          )
      },
      fail: function (res) {

      }
    });
  },

  subTap: function () {
    let that = this;
    wx.requestSubscribeMessage({
      tmplIds: ['c6_V7shOfIB_Z5ENKKXamDs_QqQH641BDQyQR6mkYEk',"5wOexb1WEOzChXuDATxrrUDc1wpVNiLtplpTv4erRAA"],
      success(res) {
        that.setData({
          textcontent: '提示：授权成功'
        })
      },
      fail(res) {
        console.log(res);
        that.setData({
          textcontent: '提示：授权失败'
        })
      }
    })
  },
  //点击一键登录
  oneClickLoginBtnClick(e) {

    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') { //用户点击拒绝
      console.log("拒绝");
    } else { //授权通过执行跳转
      console.log("同意");
      //获取手机号
      console.log(e.detail)
      console.log(e.detail.cloudID);
      //获取手机号

      //获取openid
      let that = this;
      wx.cloud.callFunction({
        name: 'getOpenid',
        data: {
          weRunData: wx.cloud.CloudID(e.detail.cloudID)
        }, // 这个 CloudID 值到云函数端会被替换
        complete: res => {
          console.log('云函数获取到的openid: ', res.result.userInfo.openId)
          
          // debugger
          let openId = res.result.userInfo.openId;
          let phone = res.result.weRunData.data.phoneNumber;
          //得到openid，从云端读取数据，若存在该用户，则登录，若不存在，则添加
          wx.setStorageSync("phone", phone)
          user.login(phone)
          .then(
            res=>{
              console.log("success",res);
              user.modifyOpenid(openId)
              .then(
                res6=>{
                  user.load_my()
                    .then(
                      res2 => {

                        getApp().globalData.sys = new System_manager();
                        getApp().globalData.sys.load()
                          .then(
                            res5 => {
                              console.log(getApp().globalData.sys)
                              console.log(res2);
                              ProjectDef.loadList()
                                .then(
                                  res4 => {
                                    console.log(res4);
                                    wx.navigateTo({
                                      url: '../check/check'
                                    });
                                  }
                                )
                            }
                          )
                      }
                    )
                }
              )
        
            }
          )
        }
      })
    };


  },
  failLogin(openId, phone) {
    let that = this;
    // wx.showToast({
    //   title: "用户初次登录请完善信息",
    //   icon: 'none',
    //   duration: 2000,
    // })
    setTimeout(function () {
      wx.reLaunch({
        url: '../wxRegister/wxRegister?openId=' + openId + '&phone=' + phone
      })
    }, 2000)
  },
  //将登录信息报错在缓存和页面中，进入下一个页面
  successLogin(data) {
    let wxUserInfo = new WXuserInfo(data);

    this.setData({
      wxUserInfo: wxUserInfo
    });

    //存在信息，成功登录
    wx.setStorage({
      key: 'wxUserInfo',
      data: wxUserInfo
    });

    let that = this;
    // wx.showToast({
    //   title: "成功登录",
    //   icon: 'success',
    //   duration: 2000,
    // })

    // debugger



    setTimeout(function () {
      // debugger
      //读取到缓存数据，根据角色进入不同页面
      let wxUserInfo = that.data.wxUserInfo;
      let wxUserInfoStr = JSON.stringify(wxUserInfo);
      switch (wxUserInfo.privilege.roleCode) {
        case "dataInput":
          wx.reLaunch({
            url: '../index-operation/index-operation?wxUserInfo=' + wxUserInfoStr
          });
          break;
        case "dataViewSection":
          wx.reLaunch({
            url: '../index/index?wxUserInfo=' + wxUserInfoStr
          });
          break;
        case "dataViewProject":
          wx.reLaunch({
            //url: '../index-project/index-project?wxUserInfo=' + wxUserInfoStr
            url: '../../subpages/DataViewProject/DataViewProject?wxUserInfo=' + wxUserInfoStr

          });
          break;
        default: break;
      }
    }, 2000)
  },
  changeLoginMode(e) {
    // debugger
    console.log(e.currentTarget.dataset.mode)
    this.setData({
      loginType: e.currentTarget.dataset.mode
    })
  },
  changeToUserPassword(e) {
    this.setData({
      loginType: "userPassword"
    });
  },
  /**
   * 账户密码登录
   */
  userPasswordBtnClick() {
    user.login(this.data.input.userId)
      .then(
        res => {
                user.load_my()
                  .then(
                    res2 => {

                      getApp().globalData.sys = new System_manager();
                      getApp().globalData.sys.load()
                        .then(
                          res5 => {
                            console.log(getApp().globalData.sys)
                            console.log(res2);
                            ProjectDef.loadList()
                              .then(
                                res4 => {
                                  console.log(res4);
                                  wx.navigateTo({
                                    url: '../check/check'
                                  });
                                }
                              )
                          }
                        )
                    }
                  )

        }
      )
  },
  /**
   * 用户账号输入
   */
  bindUserInput(e) {
    this.data.input.userId = e.detail.value;
    this.setData({
      input: this.data.input
    });
  },
  // 清空用户输入内容
  clearAccountValue() {
    // debugger
    this.setData({
      accountValue: ""
    })
  },
  /**
   * 用户密码输入
   */
  bindPasswordInput(e) {
    this.data.input.userPassword = e.detail.value;
    this.setData({
      input: this.data.input
    });
  },
  // 清空用户密码输入
  clearPasswordValue() {
    // debugger
    this.setData({
      passwordValue: ''
    })
  }
})